package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.util.NumberUtils;
import com.cskaoyan.mall.commons.util.TradeNoUtils;
import com.cskaoyan.order.biz.callback.SendEmailCallback;
import com.cskaoyan.order.biz.callback.TransCallback;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private GlobalIdGeneratorUtil globalIdGeneratorUtil;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext orderContext = (CreateOrderContext) context;
        // 1.插入订单表
        Order order = new Order();
        String orderId = null;

        try {
            orderId = globalIdGeneratorUtil.getNextSeq("orderId", 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            orderId = globalIdGeneratorUtil.getNextSeq("orderId", 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        order.setOrderId(orderId);
        order.setUserId(orderContext.getUserId());
        order.setBuyerNick(orderContext.getBuyerNickName());
        order.setPayment(orderContext.getOrderTotal());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        int orderMapperRow = orderMapper.insert(order);
        if (orderMapperRow < 1) {
            throw new BizException(
                    OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                    OrderRetCode.INIT_ORDER_EXCEPTION.getMessage()
            );
        }

        // 1.1插入唯一键
        String uniqueKey = TradeNoUtils.generateTradeNo();
        Integer uniqueKeyRow = orderMapper.updateUniqueKey(orderId,uniqueKey);
        if(uniqueKeyRow!=1){
            throw new BizException(
                    OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                    OrderRetCode.INIT_ORDER_EXCEPTION.getMessage()
            );
        }

        // 2.插入订单商品表
        List<CartProductDto> cartProductDtoList = orderContext.getCartProductDtoList();
        List<Long> buyProductIds = new ArrayList<>();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            OrderItem orderItem = new OrderItem();
            String orderItemId = null;
            try {
                orderItemId = globalIdGeneratorUtil.getNextSeq("orderItemId", 1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            orderItem.setId(orderItemId);
            orderItem.setItemId(cartProductDto.getProductId());
            orderItem.setOrderId(orderId);
            orderItem.setNum(cartProductDto.getProductNum().intValue());
            orderItem.setPrice(cartProductDto.getSalePrice().doubleValue());
            orderItem.setTitle(cartProductDto.getProductName());
            orderItem.setPicPath(cartProductDto.getProductImg());
            BigDecimal totalFee = cartProductDto.getSalePrice().multiply(new BigDecimal(cartProductDto.getProductNum()));
            orderItem.setTotalFee(totalFee.doubleValue());
            orderItem.setStatus(1);
            int orderItemMapperRow = orderItemMapper.insert(orderItem);
            if (orderItemMapperRow < 1) {
                throw new BizException(
                        OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                        OrderRetCode.INIT_ORDER_EXCEPTION.getMessage()
                );
            }
            buyProductIds.add(cartProductDto.getProductId());

        }
        orderContext.setOrderId(orderId);
        orderContext.setBuyProductIds(buyProductIds);
        return true;
    }

}
